package com.ffcc.fitness.trade.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.ffcc.fitness.base.response.JsonResult;
import com.ffcc.fitness.base.response.StatusCode;
import com.ffcc.fitness.trade.pojo.dto.TradeInsertParam;
import com.ffcc.fitness.trade.pojo.dto.TradeUpdateParam;
import com.ffcc.fitness.trade.pojo.vo.TradeVO;
import com.ffcc.fitness.trade.service.TradeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@SaIgnore
@RequestMapping("v1/trade/")
public class TradeController {
    @Autowired
    private TradeService tradeService;

    @Value("${file-path}")
    private String dirPath;

    @PostMapping("insert")
    public JsonResult insert(@RequestBody TradeInsertParam tradeInsertParam) {
        log.info("上架器械参数: {}", tradeInsertParam);
        tradeService.insert(tradeInsertParam);
        return JsonResult.ok();
    }

    @GetMapping("select")
    public JsonResult select() {
        List<TradeVO> tradeList = tradeService.select();
        return JsonResult.ok(tradeList);
    }

    /**
     * 交易模块专用的多图片上传方法
     * 支持一次性上传最多5张图片，并保存在 trade 文件夹中
     */
    @PostMapping("upload")
    public JsonResult upload(@RequestParam("files") List<MultipartFile> files) throws IOException {
        // 验证上传图片数量是否超过5张
        if (files.size() > 5) {
            return new JsonResult(StatusCode.FILE_UPLOAD_MAX_COUNT);
        }

        List<String> fileUrls = new ArrayList<>();

        // 创建 trade 专用文件夹
        File tradeDir = new File(dirPath + "/trade");
        if (!tradeDir.exists()) {
            tradeDir.mkdirs();
        }

        // 处理每一个上传的文件
        for (MultipartFile file : files) {
            // 得到原始文件名
            String fileName = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            // 创建唯一的文件名
            String newFileName = UUID.randomUUID().toString() + suffix;
            // 完整的文件保存路径
            String filePath = dirPath + "/trade/" + newFileName;

            // 保存文件
            file.transferTo(new File(filePath));
            // 保存相对路径，用于前端展示
            fileUrls.add("/trade/" + newFileName);
        }

        return JsonResult.ok(fileUrls);
    }

    /**
     * 删除已上传的交易图片
     */
    @PostMapping("remove")
    public JsonResult remove(@RequestParam("imgUrls") List<String> imgUrls) {
        for (String imgUrl : imgUrls) {
            // 删除每个图片文件
            new File(dirPath + imgUrl).delete();
        }
        return JsonResult.ok();
    }

    @GetMapping("selectById")
    public JsonResult selectById(@RequestParam Long tradeId) {
        log.info("根据交易ID查询交易详情: tradeId={}", tradeId);
        try {
            TradeVO trade = tradeService.selectById(tradeId);
            if (trade == null) {
                return new JsonResult(5005, "交易不存在");
            }
            return JsonResult.ok(trade);
        } catch (Exception e) {
            log.error("查询交易详情失败: tradeId={}", tradeId, e);
            return new JsonResult(5001, "查询失败");
        }
    }

    @GetMapping("selectByUserId")
    public JsonResult selectByUserId(@RequestParam Long userId) {
        log.info("根据用户ID查询交易列表: userId={}", userId);
        try {
            List<TradeVO> tradeList = tradeService.selectByUserId(userId);
            return JsonResult.ok(tradeList);
        } catch (Exception e) {
            log.error("查询用户交易列表失败: userId={}", userId, e);
            return new JsonResult(5001, "查询失败");
        }
    }

    @PostMapping("update")
    public JsonResult update(@RequestBody TradeUpdateParam tradeUpdateParam) {
        log.info("更新交易信息: {}", tradeUpdateParam);
        try {
            tradeService.update(tradeUpdateParam);
            return JsonResult.ok();
        } catch (Exception e) {
            log.error("更新交易信息失败", e);
            return new JsonResult(5001, "更新失败");
        }
    }

    @PostMapping("delete")
    public JsonResult delete(@RequestParam Long tradeId, @RequestParam Long userId) {
        log.info("删除交易: tradeId={}, userId={}", tradeId, userId);
        try {
            tradeService.delete(tradeId, userId);
            return JsonResult.ok();
        } catch (Exception e) {
            log.error("删除交易失败", e);
            return new JsonResult(5001, "删除失败");
        }
    }
}
